package rest.jbpm.filters; 

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;

public class TransformationFilter implements ContainerResponseFilter {

	
	private static Logger log = LoggerFactory.getLogger(ContainerResponseFilter.class);
	
	@Override
	public ContainerResponse filter(ContainerRequest request,
			ContainerResponse response) {
		
		if(request.getQueryParameters().containsKey("html")
				&& response.getEntity() instanceof String) {
			
			
			StringReader in=new StringReader((String) response.getEntity());
			StringWriter out = new StringWriter();
			
			try {
			
				int ch;
				while((ch=in.read()) != -1 && ((char)ch)!='>'){
					
					out.write(ch);
				}
				String xsltLoc = request.getBaseUri() + "resources/xslt/html.xsl";
				
				out.write("><?xml-stylesheet type='text/xsl' href='" + xsltLoc + "'?>");
			
				IOUtils.copy(in, out);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			response.setEntity(out.toString());
			return response;
		}
	
		return response;
	}
	
	
}
